<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 该页面已完成 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input
                    v-model="query.name"
                    clearable
                    placeholder="名称"
                    class="handle-input mr10"
                    @keyup.native.enter="handleSearch()"
                ></el-input>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <!-- <el-button type="danger"
                   class="handle-del"
                   @click="delAllSelection">删除</el-button> -->
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                @sort-change="sortChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="name" label="名称" align="center"></el-table-column>
                <el-table-column prop="description" label="备注" align="center"></el-table-column>

                <el-table-column prop="createTime" label="创建时间" sortable align="center"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :close-on-click-modal="false" :visible.sync="addVisible" width="50%">
            <el-form ref="addRuleForm" :model="addRuleForm" label-width="auto" :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input clearable v-model="addRuleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input clearable v-model="addRuleForm.description"></el-input>
                </el-form-item>
            </el-form>
            <el-form :model="addRuleForm" label-width="auto" :rules="rules">
                <el-form-item label="菜单授权" prop="menuAuthorizeList">
                    <el-tree
                        accordion
                        :data="addRuleForm.menuAuthorizeList"
                        show-checkbox
                        node-key="id"
                        ref="tree"
                        highlight-current
                        :props="defaultProps"
                    >
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框-->
        <el-dialog title="编辑" :close-on-click-modal="false" :visible.sync="editVisible" width="50%">
            <el-form ref="editForm" :model="editForm" label-width="auto" :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input clearable v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input clearable v-model="editForm.description"></el-input>
                </el-form-item>
            </el-form>
            <!-- 共用 addRuleForm中数据 便于初始化一些数据-->
            <el-form :model="addRuleForm" label-width="auto" :rules="rules">
                <el-form-item label="菜单授权" prop="menuAuthorizeList">
                    <el-tree
                        accordion
                        :data="addRuleForm.menuAuthorizeList"
                        show-checkbox
                        node-key="id"
                        ref="tree"
                        highlight-current
                        :props="defaultProps"
                        :default-checked-keys="menuAuthorizeSelectChecked"
                    >
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'RoleManage',
    data() {
        return {
            addrole: false,
            editrole: false,
            defaultProps: {
                children: 'permissions',
                label: 'name'
            },
            query: {
                order: '',
                orderField: '',
                pageIndex: 1,
                pageSize: 10,
                name: '',
                status: 1
            },
            tableData: [
                {
                    createBy: '',
                    createTime: '',
                    description: '',
                    id: '',
                    name: '',
                    parentId: '',
                    status: '',
                    supportChannels: [],
                    supportServices: [],
                    updateBy: '',
                    updateTime: ''
                }
            ],

            addRuleForm: {
                name: '',
                description: '',
                // 菜单授权
                menuAuthorizeList: [
                    {
                        id: '',
                        name: '',
                        permissions: []
                    }
                ],
                menuAuthorizeIdList: []
            },
            rules: {
                name: [{ required: true, message: '必填不能为空', trigger: 'blur' }],
                description: [{ required: true, message: '必填不能为空', trigger: 'blur' }],
                menuAuthorizeList: []
            },
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            pageTotal: 0,
            editForm: {
                id: '',
                name: '',
                description: ''
            },
            menuAuthorizeSelectChecked: [], // 菜单授权
            idx: -1,
            ids: [],
            array: []
        };
    },

    created() {
        this.getSysRoleData();
    },
    computed: {},
    watch: {},
    methods: {
        // 获取数据
        async getSysRoleData() {
            console.log(this.query);
            try {
                const url = '/role/query';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        name: this.query.name,
                        status: this.query.status,
                        page: this.query.pageIndex,
                        size: this.query.pageSize
                    }
                });
                console.log('角色管理列表：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.pageTotal = res.data.totalElements || 0;
                this.tableData = res.data.content;
                this.tableData.map(item => {
                    item.createTime = this.$dateFormat(item.createTime);
                });
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 表头排序
        sortChange({ column, prop, order }) {
            prop = prop === 'createTime' ? 'create_date' : prop;
            this.$set(this.query, 'orderField', prop);
            if (order === 'ascending') {
                this.$set(this.query, 'order', order.substr(0, 3));
                this.getSysRoleData();
            } else if (order === 'descending') {
                this.$set(this.query, 'order', order.substr(0, 4));
                this.getSysRoleData();
            }
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            console.log(row);
            // this.editForm = row;
            this.editVisible = true;

            this.addRuleForm.menuAuthorizeIdList = [];
            // 初始化菜单授权
            this.initMenuAuthorize(row.id);
        },
        // 初始化菜单授权
        async initMenuAuthorize(id) {
            try {
                const url = '/menu/query';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        serviceId: localStorage.getItem('code')
                    }
                });
                console.log('初始化上级菜单：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.addRuleForm.menuAuthorizeList = res.data;

                // 正确渲染菜单授权
                this.reanderMenuAuthor(id);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        async reanderMenuAuthor(id) {
            this.menuAuthorizeSelectChecked = [];
            // 获取当前用户信息 正确显示菜单授权
            try {
                const url = '/role/get';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        roleId: id,
                        serviceId: localStorage.getItem('code')
                    }
                });
                console.log('编辑角色数据：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.editForm = res.data;
                // 菜单授权
                var menuAuthorizeList = this.addRuleForm.menuAuthorizeList;
                console.log(menuAuthorizeList);
                var son = []; //所有三级菜单
                menuAuthorizeList.map(grandItem => {
                    if (grandItem.permissions && grandItem.permissions.length) {
                        grandItem.permissions.map(fatherItem => {
                            if (fatherItem.permissions && fatherItem.permissions.length) {
                                fatherItem.permissions.map(subItem => {
                                    son.push(subItem.id);
                                });
                            }
                        });
                    }
                });
                console.log('所有三级菜单:', son);
                var fatherId = []; //所有二级菜单
                menuAuthorizeList.map(grandItem => {
                    if (grandItem.permissions && grandItem.permissions.length) {
                        grandItem.permissions.map(fatherItem => {
                            fatherId.push(fatherItem.id);
                        });
                    }
                });
                console.log('所有二级菜单:', fatherId);
                var grandId = []; //所有一级菜单
                menuAuthorizeList.map(item => {
                    grandId.push(item.id);
                });
                console.log('所有一级菜单:', grandId);

                var menuIdList = res.data.permissions;
                console.log('选中的所有菜单：', menuIdList);

                //删除选中的一级菜单
                for (var i = 0; i < menuIdList.length; i++) {
                    for (var j = 0; j < grandId.length; j++) {
                        if (menuIdList[i] == grandId[j]) {
                            menuIdList.splice(i, 1);
                        }
                    }
                }
                console.log('选中的子菜单:', menuIdList);
                // 菜单授权
                this.menuAuthorizeSelectChecked = menuIdList;
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        saveEdit() {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.editOk();
                }
            });
        },
        //保存编辑
        async editOk() {
            let parentArr = this.$refs.tree.getHalfCheckedKeys(); //获取半选中状态的id
            let childArr = this.$refs.tree.getCheckedKeys(); //获取全选中的id

            this.addRuleForm.menuAuthorizeIdList = parentArr.concat(childArr); //拼接在一起
            console.log(parentArr);
            console.log(childArr);
            console.log(this.addRuleForm.menuAuthorizeIdList);

            // // 得到成功提示
            try {
                console.log(this.editForm);
                const url = '/role/update';
                let val = {
                    name: this.editForm.name,
                    roleId: this.editForm.id,
                    description: this.editForm.description,
                    serviceCode: localStorage.getItem('code'),
                    status: this.editForm.status
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('初始化角色编辑菜单：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.editrole = true;
                const url1 = '/service/update';
                let val1 = {
                    permissions: this.addRuleForm.menuAuthorizeIdList,
                    serviceCode: localStorage.getItem('code') + '_' + this.editForm.name
                };
                const { data: res1 } = await this.$http[4].post(url1, this.$objTostring(val1), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('权限：', res1);
                if (res1.code !== '0000') {
                    return;
                }
                this.$message.success('ok');
                console.log(this.editrole);
                if (this.editrole) {
                    this.getSysRoleData();
                    this.editVisible = false;
                }
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getSysRoleData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.getSysRoleData();
        },

        // 新增
        handleAdd() {
            this.addVisible = true;
            this.addRuleForm.menuAuthorizeIdList = [];
            // 初始化菜单授权
            this.initMenuAuthorize();
        },
        saveAdd() {
            this.$refs.addRuleForm.validate(valid => {
                if (valid) {
                    this.addOk();
                }
            });
        },
        async addOk() {
            let parentArr = this.$refs.tree.getHalfCheckedKeys(); //获取半选中状态的id
            let childArr = this.$refs.tree.getCheckedKeys(); //获取全选中的id
            this.addRuleForm.menuAuthorizeIdList = parentArr.concat(childArr); //拼接在一起
            console.log(parentArr);
            console.log(childArr);
            console.log(this.addRuleForm.menuAuthorizeIdList);
            // 得到成功提示
            try {
                const url = '/role/post';
                let val = {
                    name: this.addRuleForm.name,
                    description: this.addRuleForm.description,
                    serviceCode: localStorage.getItem('code'),
                    status: 1
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('角色新增：', res);
                if (res.code !== '0000') {
                    return;
                }
                // this.$message.success('操作成功1');
                this.addrole = true;

                const url1 = '/service/post';
                let val1 = {
                    permissions: this.addRuleForm.menuAuthorizeIdList,
                    serviceId: localStorage.getItem('code') + '_' + this.addRuleForm.name
                };
                const { data: res1 } = await this.$http[4].post(url1, this.$objTostring(val1), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('权限：', res1);
                if (res1.code !== '0000') {
                    return;
                }
                this.$message.success('ok');
                console.log(this.addrole);
                if (this.addrole) {
                    this.addVisible = false;
                    this.addRuleForm = {
                        name: '',
                        description: '',
                        // 菜单授权
                        menuAuthorizeList: [
                            {
                                id: '',
                                name: '',
                                permissions: []
                            }
                        ],
                        menuAuthorizeIdList: []
                    };
                    this.getSysRoleData();
                }
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.tableData = [];
            this.getSysRoleData();
        },
        // 删除操作
        handleDelete(row) {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.deleteData('/role/delete', row.id, this.getSysRoleData);
                })
                .catch(() => {});
        },
        async deleteData(url, id, callback) {
            try {
                const { data: res } = await this.$http[4].delete(url, {
                    params: {
                        roleId: id
                    }
                });
                console.log('dele:', res);
                if (res.code !== '0000') {
                    return;
                }
                this.$message.success('操作成功');
                callback();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            var ids = this.multipleSelection.map(item => {
                return item.id;
            });
            util.delete.call(this, '/sys/role', '', ids, this.getSysRoleData);
        }
    }
};
</script>

<style lang="scss">
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    width: 120px;
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
